import {
  VXETable,
  type VxeTableDefines,
  type VxeTableDataRow,
  type VxeTablePropTypes,
  type VxeTableEvents,
  type VxeGlobalMenusHandles,
  type VxeTableConstructor,
  type VxeTablePrivateMethods,
} from 'vxe-table';
import exceljs from 'exceljs';
import { useMainStore } from '@/stores/main';
import CryptoJS from 'crypto-js';
import { list } from './mock';
import { ElMessage, ElMessageBox, type Action } from 'element-plus';
const store = useMainStore();
declare module 'vxe-table' {
  export namespace VxeTableDefines {
    export interface ExtortSheetMethodParams {
      workbook: exceljs.Workbook;
      worksheet: exceljs.Worksheet;
    }
    export interface ColumnInfo {
      _row: any;
      _colSpan: number;
      _rowSpan: number;
      childNodes: VxeTableDefines.ColumnInfo[];
    }
  }
}
/**
 * 绘画水印
 * @param str 要做出水印的文字
 * @returns Base64
 */
export function getWatermark(str: string) {
  // 创建一个画布
  const can = document.createElement('canvas');
  // 设置画布的长宽
  can.width = 500;
  can.height = 220;
  const cans = can.getContext('2d')!;
  // 旋转角度
  cans.rotate((-25 * Math.PI) / 180);
  // 设置字体大小
  cans.font = '300 30px Microsoft JhengHei';
  // 设置填充绘画的颜色、渐变或者模式
  cans.fillStyle = 'rgba(130, 142, 162, 0.5)';
  // 设置文本内容的当前对齐方式
  cans.textAlign = 'center';
  // 设置在绘制文本时使用的当前文本基线
  cans.textBaseline = 'middle';
  cans.fillText(str, 80, 180);

  const dataURL = can.toDataURL('image/png');
  can.remove();
  return dataURL;
}

export const menuConfig = <VxeTablePropTypes.MenuConfig>{
  // header: {
  //   options: [
  //     [
  //       { code: 'hideColumn', name: '隐藏列', disabled: false },
  //       { code: 'showAllColumn', name: '取消所有隐藏列', disabled: false },
  //     ],
  //   ],
  // },
  body: {
    options: [
      [
        {
          code: 'fix',
          name: '置顶冻结',
          disabled: false,
          prefixIcon: 'icon-zhidingdongjie',
        },
        {
          name: '填充颜色',
          disabled: false,
          slot: 'color',
          prefixIcon: 'icon-tianchongyanse',
          children: [
            {
              code: 'backgroudColor',
              childrenCode: '#B02318',
              className: '_B02318',
              name: '#B02318',
              visible: true,
              disabled: false,
            },
            {
              code: 'backgroudColor',
              childrenCode: '#EB3223',
              className: '_EB3223',
              name: '#EB3223',
              visible: true,
              disabled: false,
            },
            {
              code: 'backgroudColor',
              childrenCode: '#F6C143',
              className: '_F6C143',
              name: '#F6C143',
              visible: true,
              disabled: false,
            },
            {
              code: 'backgroudColor',
              childrenCode: '#FFFD54',
              className: '_FFFD54',
              name: '#FFFD54',
              visible: true,
              disabled: false,
            },
            {
              code: 'backgroudColor',
              childrenCode: '#A0CD63',
              className: '_A0CD63',
              name: '#A0CD63',
              visible: true,
              disabled: false,
            },
            {
              code: 'backgroudColor',
              childrenCode: '#4EAC5B',
              className: '_4EAC5B',
              name: '#4EAC5B',
              visible: true,
              disabled: false,
            },
            {
              code: 'backgroudColor',
              childrenCode: '#4CAFEA',
              className: '_4CAFEA',
              name: '#4CAFEA',
              visible: true,
              disabled: false,
            },
            {
              code: 'backgroudColor',
              childrenCode: '#2C70BA',
              className: '_2C70BA',
              name: '#2C70BA',
              visible: true,
              disabled: false,
            },
            {
              code: 'backgroudColor',
              childrenCode: '#06215C',
              className: '_06215C',
              name: '#06215C',
              visible: true,
              disabled: false,
            },
            {
              code: 'backgroudColor',
              childrenCode: '#68379A',
              className: '_68379A',
              name: '#68379A',
              visible: true,
              disabled: false,
            },
          ],
        },
        {
          name: '字体颜色',
          disabled: false,
          slot: 'color',
          prefixIcon: 'icon-wenbenyanse',
          children: [
            {
              code: 'fontColor',
              childrenCode: '#B02318',
              className: '_B02318',
              name: '#B02318',
              visible: true,
              disabled: false,
            },
            {
              code: 'fontColor',
              childrenCode: '#EB3223',
              className: '_EB3223',
              name: '#EB3223',
              visible: true,
              disabled: false,
            },
            {
              code: 'fontColor',
              childrenCode: '#F6C143',
              className: '_F6C143',
              name: '#F6C143',
              visible: true,
              disabled: false,
            },
            {
              code: 'fontColor',
              childrenCode: '#FFFD54',
              className: '_FFFD54',
              name: '#FFFD54',
              visible: true,
              disabled: false,
            },
            {
              code: 'fontColor',
              childrenCode: '#A0CD63',
              className: '_A0CD63',
              name: '#A0CD63',
              visible: true,
              disabled: false,
            },
            {
              code: 'fontColor',
              childrenCode: '#4EAC5B',
              className: '_4EAC5B',
              name: '#4EAC5B',
              visible: true,
              disabled: false,
            },
            {
              code: 'fontColor',
              childrenCode: '#4CAFEA',
              className: '_4CAFEA',
              name: '#4CAFEA',
              visible: true,
              disabled: false,
            },
            {
              code: 'fontColor',
              childrenCode: '#2C70BA',
              className: '_2C70BA',
              name: '#2C70BA',
              visible: true,
              disabled: false,
            },
            {
              code: 'fontColor',
              childrenCode: '#06215C',
              className: '_06215C',
              name: '#06215C',
              visible: true,
              disabled: false,
            },
            {
              code: 'fontColor',
              childrenCode: '#68379A',
              className: '_68379A',
              name: '#68379A',
              visible: true,
              disabled: false,
            },
          ],
        },
        {
          divied: true,
        },
        { code: 'operate1', name: '操作一', disabled: false, prefixIcon: 'icon-qitacaozuo' },
        { code: 'operate2', name: '操作二', disabled: false, prefixIcon: 'icon-qitacaozuo' },
      ],
    ],
  },
  visibleMethod(data) {
    console.log(data);
    const { options, row, column } = data;
    /**
    | 置顶冻结/取消冻结 |  | 对本行属性进行置顶并冻结，翻页和上下滚动冻结显示本列。 重新进行前置查询后，冻结效果取消。 |
    | --- | --- | --- |
    | 填充颜色（颜色icon） | 无填充色/wps常规10色/其他颜色 | 二级功能选定颜色后，默认使用选定颜色。 |
    | 字体颜色（颜色icon） | 无填充色/wps常规10色/其他颜色 | 二级功能选定颜色后，默认使用选定颜色。  |
    | 操作一 |  | 操作栏的的功能按钮，包括更多缩略的功能按钮，在此处显示并功能一致。 |
    | 操作二 |  |  |
    | 操作三 |  |  |
     */
    const fixRow = Array.from(store.$state.fixRow ?? []);
    const isMatch = fixRow.some(item => equalRow(item, row));
    options.forEach(list => {
      list.forEach(item => {
        if (item.code === 'fix') {
          item.name = isMatch ? '取消冻结' : '置顶冻结';
        }
        if (item.name === '填充颜色') {
          item.lastColor = store.$state.lastBackgroundColor;
        }
        if (item.name === '字体颜色') {
          item.lastColor = store.$state.lastFontColor;
          if (column?.field === 'status') {
            item.disabled = true;
          } else {
            item.disabled = false;
          }
        }
      });
    });
    return true;
  },
};
export function setCellStyle({
  row,
  rowIndex,
  $rowIndex,
  column,
  columnIndex,
  $columnIndex,
}: {
  row: any;
  rowIndex: number;
  $rowIndex: number;
  column: any;
  columnIndex: number;
  $columnIndex: number;
}): any {
  return {
    background: store.getBackgroundColor(row.xuhao, $columnIndex),
    color: store.getFontColor(row.xuhao, $columnIndex),
  };
}
export function vxeMenuRegister() {
  VXETable.menus.mixin({
    fix: {
      menuMethod(params: VxeGlobalMenusHandles.MenuMethodParams, event: Event) {
        const fixRow = Array.from(store.$state.fixRow ?? []);
        const someIndex = fixRow.findIndex(item => equalRow(item, params.row));
        if (someIndex === -1) {
          store.$state.fixRow.add(JSON.parse(JSON.stringify(params.row)));
        } else {
          store.$state.fixRow.clear();
          fixRow.splice(someIndex, 1);
          fixRow.forEach(e => store.$state.fixRow.add(JSON.parse(JSON.stringify(e))));
        }
        (document.querySelector('.tableWrap') as HTMLElement)?.style.setProperty(
          '--table-fix-row',
          store.$state.fixRow.size + ''
        );
        store.$state.focusRefresh = Date.now();
      },
    },
    backgroudColor: {
      menuMethod(params: VxeGlobalMenusHandles.MenuMethodParams, event: Event) {
        if (params.menu.childrenCode === 'none') {
          store.setBackgroundColor(params.row.xuhao, params.columnIndex, void 0);
        } else {
          store.setBackgroundColor(params.row.xuhao, params.columnIndex, params.menu.childrenCode);
        }
      },
    },
    fontColor: {
      menuMethod(params: VxeGlobalMenusHandles.MenuMethodParams, event: Event) {
        if (params.menu.childrenCode === 'none') {
          store.setFontColor(params.row.xuhao, params.columnIndex, void 0);
        } else {
          store.setFontColor(params.row.xuhao, params.columnIndex, params.menu.childrenCode);
        }
      },
    },
    operate1: {
      menuMethod() {
        ElMessageBox.alert('是否确认执行操作一', '提示', {
          // if you want to disable its autofocus
          // autofocus: false,
          confirmButtonText: 'OK',
          callback: (action: Action) => {
            ElMessage({
              type: 'info',
              message: `action: ${action}`,
            });
          },
        });
      },
    },
    operate2: {
      menuMethod() {
        ElMessageBox.alert('是否确认执行操作二', '提示', {
          // if you want to disable its autofocus
          // autofocus: false,
          confirmButtonText: 'OK',
          callback: (action: Action) => {
            ElMessage({
              type: 'info',
              message: `action: ${action}`,
            });
          },
        });
      },
    },
  });
}
export function vxeCommandRegister() {
  // 自定义导出指令
  VXETable.commands.add('exportXLSX', {
    commandMethod({ code, button, $table },{header}) {
      const base64 = getWatermark('国网用采项目');
      const fixRow = Array.from(store.$state.fixRow ?? []);

      $table.exportData({
        filename: '国网用采项目信息表',
        sheetName: 'Sheet1',
        type: 'xlsx',
        useStyle: true, //是否导出样式
        isFooter: false, //是否导出表尾
        isHeader: true, //是否导出表头
        download: true,
        // data: fixRow.concat(list.filter(e => !fixRow.some(item => equalRow(item, e)))),
        data:header.getTableData().tableData.concat($table.getTableData().tableData),
        //过滤哪列字段导出
        columnFilterMethod: function (param: {
          column: VxeTableDefines.ColumnInfo;
          $columnIndex: number;
        }) {
          //0是checkbox 1是序号列不导出
          return (
            param.$columnIndex !== 0 &&
            !(
              param.column.field.startsWith('_') ||
              param.column.title.startsWith('_') ||
              param.column.title === '操作'
            )
          );
        },
        //过滤哪行字段导出
        dataFilterMethod: function (param: { row: any; $rowIndex: number }) {
          return true;
        },
        //sheetMethod方法中用的是exceljs插件文档里的语法
        sheetMethod: function (params: VxeTableDefines.ExtortSheetMethodParams) {
          const image = params.workbook.addImage({ base64, extension: 'png' });

          //合并单元格
          //vxe-table
          //row起始行下标col起始列下标
          //rowspan合并目标的相对行下标(相对于起始行的下标)
          //colspan合并目标的列下标(下标从0开始)
          //mergeCells: [
          //合并单元格
          //{row:1,col:2,rowspan:0,colspan:4),
          //exceljs
          //按开始行,开始列,结束行,结束列合并
          // worksheet.mergeCells(1,4);
          // this.mergeCells.forEach(mergeCell => {
          //     const {row,col,rowspan,colspan} = mergeCell
          //     params.worksheet.mergeCells(row, col, row + rowspan, colspan);
          // })
          params.worksheet.views = [
            {
              state: 'frozen',
              xSplit: params.columns.filter(e => e.fixed === 'left').length,
              ySplit: fixRow.length + 1,
            },
          ];
          params.worksheet.eachRow(row => {
            row.eachCell((cell, colNumber) => {
              cell.border = {
                top: { style: 'thin' },
                left: { style: 'thin' },
                bottom: { style: 'thin' },
                right: { style: 'thin' },
              };
              //设置字体
              cell.font = {
                size: 9,
                color: {
                  argb: (store.getFontColor(row.getCell(1).text, colNumber) ?? '#000000')
                    .replace('#', '')
                    .padStart(8, 'F'),
                },
              };
              //设置自动换行和文字水平居中
              // cell.alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
              //设置单元格样式
              const bg = store.getBackgroundColor(row.getCell(1).text, colNumber);
              cell.fill = {
                type: 'pattern',
                pattern: (!!bg && 'solid') || 'none',
                fgColor: {
                  argb: (store.getBackgroundColor(row.getCell(1).text, colNumber) ?? '#000000')
                    .replace('#', '')
                    .padStart(8, 'F'),
                },
              };
            });
          });
          // 添加背景图片
          params.worksheet.addBackgroundImage(image);
        },
      });
    },
  });
}

export function md5(text: any) {
  if (!text) return '';
  if (typeof text !== 'string') {
    text = JSON.stringify(text);
  }
  return CryptoJS.MD5(text).toString();
}
export function equalRow(row1: any, row2: any) {
  if (!row1 || !row2) {
    return false;
  }
  const key1 = Object.keys(row1).filter(e => !e.startsWith('_'));
  const key2 = Object.keys(row2).filter(e => !e.startsWith('_'));
  if (key1.length !== key2.length) {
    return false;
  }
  if (md5(key1) !== md5(key2)) {
    return false;
  }
  const newRow1 = Object.entries(key1.map(e => [e, row1[e]]));
  const newRow2 = Object.entries(key1.map(e => [e, row2[e]]));

  return md5(newRow1) === md5(newRow2);
}
export function setRowStyle({
  row,
}: {
  $table: VxeTableConstructor<any> & VxeTablePrivateMethods<any>;
  row: any;
  rowIndex: number;
  $rowIndex: number;
  _rowIndex: number;
}): any {
  const fixRow = Array.from(store.$state.fixRow ?? []);
  const index = fixRow.findIndex(item => equalRow(item, row));
  if (index > -1) {
    return {
      'background-color': ' #EAF4F4!important',
      'box-shadow': 'inset -1px -1px 0px 0px #D9D9D9',
      // position: 'sticky',
      // top: `${index * store.$state.rowHeight}px`,
      // 'z-index': 2,
    };
  }
  return {};
}
export function getDomNode() {
  const documentElement = document.documentElement;
  const bodyElem = document.body;
  return {
    scrollTop: documentElement.scrollTop || bodyElem.scrollTop,
    scrollLeft: documentElement.scrollLeft || bodyElem.scrollLeft,
    visibleHeight: documentElement.clientHeight || bodyElem.clientHeight,
    visibleWidth: documentElement.clientWidth || bodyElem.clientWidth,
  };
}
